package servlet;

import dao.UserDao;
import dao.daoimpl.UserDaoImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//找回密码服务器
@WebServlet(name="ForgetServlet",urlPatterns = "/ForgetServlet")
public class ForgetServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        String account=request.getParameter("userAccount");/*获取账号*/
        String password=request.getParameter("userPassword");/*获取新密码*/
        String code1=request.getParameter("userSecurityCode");/*获取验证码*/
        UserDao userDao= new UserDaoImpl();
        Cookie [] cookies=request.getCookies();
        String code2=null;
        /*接收验证码*/
        for(Cookie cookie:cookies) {
            if("code".equals(cookie.getName())) {
                code2=cookie.getValue();
            }
        }
        if(code1.equals(code2)) {/*核实验证码*/
            if(userDao.forget(account,password)) {/*进行密码更新*/
                request.getRequestDispatcher("loginPage.jsp").forward(request, response);/*返回登录界面，重新登录*/
            }else{
                request.setAttribute("fail","找回失败，请稍后重试");/*更新密码失败*/
            }
        }
        else{
            request.setAttribute("error","验证码错误");/*验证码错误*/
            request.getRequestDispatcher("forgetPage.jsp").forward(request,response);/*重新找回*/
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
